package flc.ast.utils;

import android.content.Context;
import android.os.Handler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.util.Base64;
import java.io.FileOutputStream;
import java.io.IOException;

public class ResumePdfGenerateUtil {
    private Context context;
    private WebView webView;
    private String pdfPath;
    private OnPdfGeneratedListener listener;
    private static final int PDF_GENERATION_DELAY = 2000;

    // 回调接口
    public interface OnPdfGeneratedListener {
        void onSuccess(String pdfPath);
        void onFailure(Exception e);
    }

    public ResumePdfGenerateUtil(Context context, WebView webView) {
        this.context = context;
        this.webView = webView;
        initWebSettings();
    }

    // 初始化WebView设置
    private void initWebSettings() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webView.setInitialScale(90);
    }

    // 加载HTML并生成PDF
    public void loadHtmlAndGeneratePdf(String htmlContent, String pdfPath, OnPdfGeneratedListener listener) {
        this.pdfPath = pdfPath;
        this.listener = listener;

        webView.loadDataWithBaseURL(null, htmlContent, "text/html", "UTF-8", null);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                generatePdf();
            }
        });
    }

    // 生成PDF的核心方法
    private void generatePdf() {
        webView.evaluateJavascript("onGeneratePDF();", null);

        new Handler().postDelayed(() -> {
            webView.evaluateJavascript("window.pdfData", value -> {
                try {
                    if (value == null || value.isEmpty()) {
                        throw new Exception("PDF生成失败，返回数据为空");
                    }

                    String base64 = value.replaceAll("^\"|\"$", "");
                    String pureBase64 = base64.replaceFirst("data:application/pdf;filename=generated.pdf;base64,", "");
                    byte[] pdfBytes = Base64.decode(pureBase64, Base64.DEFAULT);

                    savePdfToFile(pdfBytes);
                    if (listener != null) {
                        listener.onSuccess(pdfPath);
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onFailure(e);
                    }
                }
            });
        }, PDF_GENERATION_DELAY);
    }

    // 保存PDF文件
    private void savePdfToFile(byte[] pdfBytes) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(pdfPath)) {
            fos.write(pdfBytes);
        }
    }
}